import React, { useRef, useEffect } from "react";
import { Editor } from "@toast-ui/react-editor";
import "@toast-ui/editor/dist/toastui-editor.css";
import { message } from "antd";
import request from "@/services/interceptors";
const imgUrl = import.meta.env.VITE_APP_IMG_URL;
type ProFormWangEditorProps = {
  value?: string;
  onChange?: (value: string) => void;
};

const ProFormWangEditor: React.FC<ProFormWangEditorProps> = ({
  value,
  onChange,
}) => {
  const editorRef = useRef<any>(null);

  // 初始化编辑器内容
  useEffect(() => {
    if (editorRef.current) {
      // 设置初始内容
      const editorInstance = editorRef.current.getInstance();
      editorInstance.setHTML(value ?? "");
    }
  }, [value]);

  // 处理图片上传
  const handleImageUpload = async (file: File, callback: Function) => {
    try {
      // const formData = new FormData();
      // formData.append("file", blob);

      // 向后端发送图片上传请求
      const { data } = await request.sgks.fileUploadCreate({ file });
      const url = `${imgUrl}${data}`;
      callback(url);
    } catch (error) {
      message.error("图片上传失败");
      callback("");
    }
  };

  // 内容变化时的回调
  const handleChange = async () => {
    if (editorRef.current && onChange) {
      const editorInstance = editorRef.current.getInstance();
      let html = editorInstance.getHTML();

      // 查找所有 base64 图片
      const imgRegex = /<img[^>]+src="([^">]+)"/g;
      let match;
      let needUpdate = false;

      while ((match = imgRegex.exec(html)) !== null) {
        const src = match[1];
        if (src.startsWith("data:image/")) {
          // base64 图片，自动上传
          try {
            // 将 base64 转为 Blob
            const arr = src.split(",");
            const mime = arr[0].match(/:(.*?);/)[1];
            const bstr = atob(arr[1]);
            let n = bstr.length;
            const u8arr = new Uint8Array(n);
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
            }
            const file = new File([u8arr], "pasted.png", { type: mime });

            // 上传图片
            const { data } = await request.sgks.fileUploadCreate({ file });
            if (data.url) {
              // 替换 HTML 中的 base64 为新图片地址
              html = html.replace(src, data.url);
              needUpdate = true;
            }
          } catch (e) {
            message.error("自动上传图片失败");
          }
        }
      }

      if (needUpdate) {
        // 更新编辑器内容
        editorInstance.setHTML(html);
      }
      onChange(html);
    }
  };

  return (
    <div className="toast-editor-wrapper">
      <Editor
        ref={editorRef}
        initialValue={value || ""}
        previewStyle="vertical"
        height="200px"
        initialEditType={["wysiwyg"]}
        hideModeSwitch={true}
        useCommandShortcut={true}
        onChange={handleChange}
        hooks={{
          addImageBlobHook: handleImageUpload,
        }}
        toolbarItems={[
          ["heading", "bold", "italic", "strike"],
          ["hr", "quote"],
          ["ul", "ol", "indent", "outdent"],
          ["table", "image", "link"],
        ]}
      />
    </div>
  );
};

export default ProFormWangEditor;
